<template>
	<view class="container">
	  <view class="chat-window" id="chat-window">
		<text class="message-text">{{ messages }}</text>
	  </view>
	  <view class="message-input">
		<textarea v-model="userMessage" placeholder="输入你的消息..."></textarea>
		<button @click="sendMessage">发送</button>
	  </view>
	</view>
  </template>
  
  <script>
  import { createChatInstance } from '@/api/coze.js';

  export default {
	data() {
	  return {
		messages: '', // 存储对话的消息文本
		userMessage: '', // 存储用户输入的消息
		chatInstance: null
	  };
	},
	created() {
	  // 初始化聊天实例
	  const botId = '7474140345551863834';
	  const userId = 'sheliming';
	  const accessToken = 'pat_ugtJNBYOtBsPwdeY4JbO5WFVT9GzpOK7xgXnUcgTF2FdWyNbNzvhrHqW0OwsoXb6';
	  this.chatInstance = createChatInstance(botId, userId, accessToken);
	},
	methods: {
	  appendMessage(content) {
		this.messages += content;
		this.$nextTick(() => {
		  this.scrollToBottom();
		});
	  },

	  scrollToBottom() {
		const query = uni.createSelectorQuery().in(this);
		query.select('#chat-window').boundingClientRect((rect) => {
		  uni.pageScrollTo({
			scrollTop: rect.height,
			duration: 300
		  });
		}).exec();
	  },

	  async sendMessage() {
		if (!this.userMessage.trim()) return;

		// 添加用户消息到聊天窗口
		this.appendMessage(this.userMessage);
		const message = this.userMessage;
		this.userMessage = '';

		// 发送消息并处理响应
		try {
		  await this.chatInstance.sendMessage(
			message,
			// 消息回调
			(content) => {
			  this.appendMessage(content);
			},
			// 错误回调
			(error) => {
			  console.error('聊天错误:', error);
			  uni.showToast({
				title: '对话失败，请稍后重试',
				icon: 'none'
			  });
			}
		  );
		} catch (error) {
		  console.error('发送消息失败:', error);
		}
	  }
	}
  }
  </script>
  
  <style scoped>
  .container {
	display: flex;
	flex-direction: column;
	height: 100%;
  }
  
  .chat-window {
	flex: 1;
	padding: 10px;
	overflow-y: auto;
	background-color: #f5f5f5;
  }
  
  .message-text {
	white-space: pre-wrap;
	word-break: break-word;
  }
  
  .message-input {
	display: flex;
	align-items: center;
	padding: 10px;
	background-color: #ffffff;
  }
  
  textarea {
	flex: 1;
	padding: 10px;
	border: 1px solid #dcdcdc;
	border-radius: 4px;
  }
  
  button {
	margin-left: 10px;
	padding: 10px 15px;
	background-color: #4caf50;
	color: white;
	border: none;
	border-radius: 4px;
	cursor: pointer;
  }
  
  button:disabled {
	background-color: #9e9e9e;
  }
  </style>
  